import React, {
    Component,
} from 'react';
import LinearGradient from 'react-native-linear-gradient';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    StatusBar,
    NativeModules,
    ScrollView,
    Switch, DeviceEventEmitter, ActivityIndicator,
    ToastAndroid,
    Clipboard,
    Alert,
    FlatList
} from 'react-native';

import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Header from '../../components/header';
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
let navigation

let pageSize = 20
let pageNo = 1;
let itemNo = 0;

export default class FoursQueryCostRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataArray: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
        }
    }

    componentDidMount() {
        setTimeout(() => {
            this.getFoursQueryCostRecords(true)
        }, 250);
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'历史账单'} ></Header>
                
                {this.renderList()}

            </View>
        )
    }

    renderList() {
        return (
            <View style={{ flex: 1}}>
                <FlatList
                    data={this.state.dataArray}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListHeaderComponent={this.renderHeader.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <View key={index} style={styles.itemContain}>
                <Text style={styles.itemTypeText}>{item.value.tradeTypeName}</Text>
                <Text style={styles.itemTimeText}>{item.value.createTime}</Text>
                <Text style={styles.itemMoneyText}>{(item.value.isIncome ? '+':'-')+parseFloat(item.value.totalAmountYuan).toFixed(2)}</Text>
                {
                    this.state.dataArray.length - 1 > index ?
                        <View style={styles.itemSepLine} />
                        :
                        null
                }

            </View>
        )
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderHeader() {
        return (
            <View style={styles.header}>
            </View>
        );
    }

    renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    refreshData = () => {
        this.getFoursQueryCostRecords(true);
    }

    _onEndReached() {
        if (this.state.dataArray.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getFoursQueryCostRecords(false);
    }

    getFoursQueryCostRecords(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
            merchantName: Constant.userInfo.merchantName,
            tradeType: 1,
        }
        HttpUtils.postRequest(HttpUrls.maintenanceOrderList, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ dataArray: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            dataArray: this.state.dataArray.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    itemContain: {
        paddingHorizontal: 10,
        width: '100%',
        height: 66,
        backgroundColor: '#fff',
        flexDirection: 'column',
        justifyContent: 'center'
    },
    itemTypeText: {
        color: '#222222',
        fontSize: 14
    },
    itemTimeText: {
        marginTop: 10,
        color: '#999999',
        fontSize: 12
    },
    itemMoneyText: {
        position: 'absolute',
        right: 10,
        color: '#FB3D3C',
        fontSize: 16
    },
    itemSepLine: {
        position: 'absolute',
        bottom: 0,
        left: 10,
        width: '100%',
        height: 0.5,
        backgroundColor: '#E4E4E4'
    },

    header: {
        width: '100%',
        height:10,
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },
})